// 引入expres
const express = require("express")
// 引入路由模块
const router = express.Router()
// 引入加密模块
const bcrypt = require("bcryptjs")
// 引入token模块
const jwt = require("jsonwebtoken")
const {
  signkey
} = require("../config/token")
// 引入token验证模块
const {
  verifyToken
} = require("../config/token.js")

// 引入数据库
const connection = require("../db/sql.js")
const moment = require("moment")

const {
  ERROR_MSG
} = require("../config/global")

// 注册用户信息
router.post("/register", (req, res) => {
  const findOneSQL = `SELECT s_user.loginname FROM s_user WHERE s_user.loginname = '${req.body.loginname}' `
  connection.query(findOneSQL, (err, result) => {
    if (result.length > 0) {
      return res.reply_error(ERROR_MSG.ILLEGAL_ARGUMENT_ERROR, "用户名重复")
    } else {
      // 使用请求体里的数据直接构造模型数据
      const newUser = req.body
      // bcrypt加密密码
      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newUser.password, salt, function (err, hash) {
          if (err) throw err
          newUser.password = hash

          const registerSQL = `INSERT INTO s_user VALUES (NULL,'${
            newUser.loginname
          }','${newUser.realname}','${newUser.password}',${newUser.role},'${
            newUser.avatar
          }','${newUser.phone}','${newUser.email}',${newUser.sex},${
            newUser.status
          },'${moment().format("YYYY-MM-DD HH:mm:ss")}')`

          // 保存数据库
          connection.query(registerSQL, (err, result) => {
            if (err) {
              console.log(err)
            } else {
              res.reply_success()
            }
          })
        })
      })
    }
  })
})

router.get("/test", (req, res) => {
  const data = verifyToken(res, req.headers.authorization)
  console.log(data)
  res.send({
    a: data,
  })
})
// 获取用户信息
router.get("/userInfo", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  const userInfoSQL = `SELECT id,loginname,realname,avatar,phone,email,sex from s_user WHERE id = ${userInfo.id}`
  connection.query(userInfoSQL, (err, result) => {
    if (result.length > 0) {
      res.reply_success({
        userInfo: result[0],
      })
    }
  })
})

// 登录
router.post("/login", (req, res) => {
  // 查找数据库信息
  const loginname = req.body.loginname
  const password = req.body.password
  const findOneSQL = `SELECT * FROM s_user WHERE s_user.loginname = '${loginname}' `

  connection.query(findOneSQL, (err, result) => {
    if (result.length > 0) {
      const user = result[0]

      // bcrypt 解码匹配
      bcrypt.compare(password, user.password).then((data) => {
        if (data) {
          // jwt.sign('规则','加密的名字','过期时间','回调函数')
          jwt.sign({
              id: user.id,
              role: user.role,
              loginname: user.loginname,
            },
            signkey, {
              expiresIn: 3600,
            },
            (err, token) => {
              res.reply_success({
                avatar: user.avatar,
                role: user.role,
                name: user.realname,
                token: "Bearer " + token, //Bearer 一定要加，注意后面有一个空格
              })
            }
          )
        } else {
          res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "账号或密码错误")
        }
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "账号或密码错误")
    }
  })
})

router.get("/auth", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  const authSQL = `SELECT auth from s_role WHERE id = (SELECT role from s_user WHERE id = ${userInfo.id})`;
  connection.query(authSQL, (err, result) => {
    if (err) {
      res.reply_error(ERROR_MSG.UNKNOWN_ERROR, err.message);
    }

    if (result.length > 0) {
      res.reply_success(result[0])
    }
  })
})

module.exports = router